package com.hsmw.api.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hsmw.api.mapper.*;
import com.hsmw.api.utils.GaoDeInfoUtils;
import com.hsmw.api.vo.DriverAndVehicleVO;
import com.hsmw.api.vo.HomeVolume;
import com.hsmw.common.base.BaseService;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.constant.HtnUserRoleEnum;
import com.htn.common.core.constant.HtnUserTypeEnum;
import com.hsmw.api.utils.CommonUtils;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.vo.GpsInfoEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author WD
 */
@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class HsmwLeasingCompanyService extends BaseService<HsmwLeasingCompanyMapper, HsmwLeasingCompany> {

	@Autowired
	private HsmwLeasingCompanyMapper hsmwLeasingCompanyMapper;
	@Autowired
	private HsmwVehicleMapper hsmwVehicleMapper;
	@Autowired
	private HsmwUserDriverMapper hsmwUserDriverMapper;

	@Autowired
	private HsmwUserDriverService hsmwUserDriverService;

	@Autowired
	private HsmwLeasingCompanyRuleMapper hsmwLeasingCompanyRuleMapper;
	@Autowired
	private HsmwComplainMapper hsmwComplainMapper;


	@Autowired
	private HsmwVehicleService hsmwVehicleService;

	@Autowired
	private HsmwItemService hsmwItemService;

	@Autowired
	private HsmwOrderBalanceMapper hsmwOrderBalanceMapper;

	@Autowired
	private HsmwConstructionPositionService hsmwConstructionPositionService;

	@Autowired
	private HsmwConcreteInfoMapper hsmwConcreteInfoMapper;

	@Autowired
	private HsmwOrderService hsmwOrderService;



	@Autowired
	private HsmwHtnUserService hsmwHtnUserService;


	public IPage<HsmwLeasingCompany> getLeasingCompanyPage(IPage page, HsmwLeasingCompany hsmwLeasingCompany) {
		return hsmwLeasingCompanyMapper.selectPageVo(page, hsmwLeasingCompany.getName(), hsmwLeasingCompany.getLinkMan(), hsmwLeasingCompany.getTel());
	}

	public Map getLeasingCompanyById(String id,String month,String driverVolume) {
		Map map = new HashMap();
		//公司信息
		HsmwLeasingCompany h = hsmwLeasingCompanyMapper.findLeasingCompanyById(id);
		map.put("company",h);
		// 泵车信息
		List<DriverAndVehicleVO> driverAndVehicleVOS = hsmwVehicleMapper.findVehicleInfoList(id);
		for (DriverAndVehicleVO driverAndVehicleVO : driverAndVehicleVOS) {
			GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(driverAndVehicleVO.getImeiNum(),driverAndVehicleVO.getFlag(),driverAndVehicleVO.getIdentifyingCode());
			if (com.htn.common.core.utils.StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
				driverAndVehicleVO.setMobileLocate(entity.getGpsLon() + "," + entity.getGpsLat());
			}
			if(StringUtils.isNotBlank(driverAndVehicleVO.getMobileLocate())){
				String nameByGps = GaoDeInfoUtils.gaodeGetNameByGps(driverAndVehicleVO.getMobileLocate());
				driverAndVehicleVO.setVehicleAddress(nameByGps);
			}
		}
		map.put("vehicle",driverAndVehicleVOS);
		// 司机信息
		List<DriverAndVehicleVO>  andVehicleVOS = hsmwUserDriverMapper.findDriverInfoList(id);
		map.put("driver",andVehicleVOS);
		List<HsmwLeasingCompanyRule> hsmwLeasingCompanyRules = hsmwLeasingCompanyRuleMapper.selectList(new LambdaQueryWrapper<HsmwLeasingCompanyRule>().eq(HsmwLeasingCompanyRule::getLeasingCompanyId, id));
		map.put("rule",hsmwLeasingCompanyRules);
		Double sumDriverVolume =  0.0;
		Double sumComfirmVolume = 0.0;
		Long sumComplainCount = 0L;
		List<HsmwOrderBalance> relationOrderVos = hsmwVehicleMapper.findRelationOrderList(id,month,driverVolume);
		for (HsmwOrderBalance relationOrderVo : relationOrderVos) {

			String relationId = relationOrderVo.getRelationId();
			List<HsmwComplain> hsmwComplains = hsmwComplainMapper.selectList(new LambdaQueryWrapper<HsmwComplain>().eq(HsmwComplain::getOrderId, relationId));
			if(CollectionUtil.isNotEmpty(hsmwComplains)){
				sumComplainCount += hsmwComplains.size();
			}
			String confirmVolume = relationOrderVo.getSettlementVolume();
			String driverVolume1 = relationOrderVo.getRealVolume();
			sumDriverVolume += Double.valueOf(driverVolume1);
			sumComfirmVolume += Double.valueOf(confirmVolume);
		}

		h.setSumComplainCountsumVolume(sumComplainCount);
		map.put("SumDriverVolume",String.format("%.1f",sumDriverVolume));
		map.put("SumConfirmVolume",String.format("%.1f",sumComfirmVolume));
		map.put("orderList",relationOrderVos);
		return map;
	}


	public int saveOrUpdateLeasingCompany(HsmwLeasingCompany hsmwLeasingCompany) {
		int result;
		if (StrUtil.isBlank(hsmwLeasingCompany.getId())) {
			HsmwHtnUser user = new HsmwHtnUser();
			user.setOwnCompanyName(hsmwLeasingCompany.getName());
			user.setType(HtnUserTypeEnum.COMPANY.getValue());
			user.setName(hsmwLeasingCompany.getLinkMan());
			user.setUsername(hsmwLeasingCompany.getTel());
			user.setEnabled(true);
			String companyId = CommonUtils.generateId(hsmwLeasingCompany);
			hsmwLeasingCompany.setId(companyId);
			String userId = CommonUtils.generateId(user);
			hsmwLeasingCompany.setUserId(userId);
			result = hsmwLeasingCompanyMapper.insert(hsmwLeasingCompany);
			user.setOwnCompanyId(companyId);
			user.setId(userId);
			user.setOwnCompanyName(hsmwLeasingCompany.getName());
			user.setRoleType(HtnUserRoleEnum.LEADING.getValue());
			hsmwHtnUserService.save(user);
		} else {
			HsmwLeasingCompany company = hsmwLeasingCompanyMapper.findLeasingCompanyById(hsmwLeasingCompany.getId());
			result = hsmwLeasingCompanyMapper.updateById(hsmwLeasingCompany);
		/*	HsmwUser userInfo = hsmwUserService.getHsmwUserById(company.getUserId());
			if(StringUtils.isNotBlank(hsmwLeasingCompany.getTel())){
				userInfo.setUsername(hsmwLeasingCompany.getTel());
			}
			if(StringUtils.isNotBlank(hsmwLeasingCompany.getLinkMan())){
				userInfo.setName(hsmwLeasingCompany.getLinkMan());
			}
			hsmwUserService.updateById(userInfo);*/
			List<HsmwVehicle> hsmwVehicles = hsmwVehicleMapper.selectList(new LambdaQueryWrapper<HsmwVehicle>().eq(HsmwVehicle::getLeasingCompanyId, hsmwLeasingCompany.getId()));
			for (HsmwVehicle hsmwVehicle : hsmwVehicles) {
				hsmwVehicle.setLeasingCompanyId(hsmwLeasingCompany.getId());
				hsmwVehicle.setLeasingCompanyName(hsmwLeasingCompany.getName());
			}
			hsmwVehicleService.updateBatchById(hsmwVehicles);
		}
		return result;
	}

	public List<HsmwLeasingCompany> getLeasingCompanySelect() {
		LambdaQueryWrapper<HsmwLeasingCompany> queryWrapper = new LambdaQueryWrapper<>();
		return hsmwLeasingCompanyMapper.selectList(queryWrapper);
	}

	public void updateLeasingCompanyVehicle(String leasingCompanyId, String vehicleIdStr) {
		HsmwLeasingCompany hsmwLeasingCompany = hsmwLeasingCompanyMapper.selectById(leasingCompanyId);
		List<HsmwVehicle> hsmwVehicleList = hsmwVehicleMapper.selectList(
				Wrappers.lambdaQuery(HsmwVehicle.class)
						.eq(HsmwVehicle::getLeasingCompanyId, leasingCompanyId)
		);
		hsmwVehicleList.forEach(hsmwVehicle -> {
			hsmwVehicle.setLeasingCompanyId("");
			hsmwVehicle.setLeasingCompanyName("");
			hsmwVehicleMapper.updateById(hsmwVehicle);
		});
		if (!StrUtil.isEmptyIfStr(vehicleIdStr)) {
			List<HsmwVehicle> hsmwVehicles = hsmwVehicleMapper.selectList(Wrappers.lambdaQuery(HsmwVehicle.class).in(HsmwVehicle::getId, Arrays.stream(vehicleIdStr.split(",")).collect(Collectors.toSet())));
			hsmwVehicles.forEach(hsmwVehicle -> {
				hsmwVehicle.setLeasingCompanyId(leasingCompanyId);
				hsmwVehicle.setLeasingCompanyName(hsmwLeasingCompany.getName());
				hsmwVehicleMapper.updateById(hsmwVehicle);
			});
		}
	}

	public List<HomeVolume> findVehicleVolumeByMonth(String id,String month) {
		return hsmwLeasingCompanyMapper.findVehicleVolumeByMonth(id,month);
	}

	public List<HomeVolume> findItemVolumeByMonth(String id,String month) {
		return hsmwLeasingCompanyMapper.findItemVolumeByMonth(id,month);
	}

	/**
	 * 编辑
	 * @param hsmwOrderBalance
	 * @return
	 */
	public DataResponse updateOrderBalance(HsmwOrderBalance hsmwOrderBalance) {

		if(hsmwOrderBalance == null){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"传递数据不可为空");
		}
		if(StringUtils.isBlank(hsmwOrderBalance.getId())){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"id不可为空");
		}
		HsmwOrderBalance orderBalance = hsmwOrderBalanceMapper.selectById(hsmwOrderBalance.getId());
		if(StringUtils.isNotBlank(hsmwOrderBalance.getWriteVolume()) && !StringUtils.equals("0",hsmwOrderBalance.getWriteVolume())){
			// 如果修改的票据方量不为空
			//产值方量优先等于票据方量如票据方量为空则等于报表方量
			hsmwOrderBalance.setOutputVolume(hsmwOrderBalance.getWriteVolume());

			Double write = Double.valueOf(hsmwOrderBalance.getWriteVolume());
			Double real = Double.valueOf(orderBalance.getRealVolume());
			Double sub = null;
			sub = real - write;
			String str1 = String.format("%.1f",sub);
			hsmwOrderBalance.setDifferenceVolume(str1);
			Double driverVolume = Double.parseDouble(hsmwOrderBalance.getWriteVolume());
			Double worktime = Double.parseDouble(orderBalance.getWorkTime());
			if(worktime > 10){
				Double aLong = 100.0;
				aLong = aLong + (worktime - 10)*10;
				if(aLong > driverVolume){
					hsmwOrderBalance.setSettlementVolume(String.valueOf(aLong));
				}else {
					hsmwOrderBalance.setSettlementVolume(String.valueOf(driverVolume));
				}
			}else {
				Long aLong = 100L;
				if(aLong > driverVolume){
					hsmwOrderBalance.setSettlementVolume(String.valueOf(aLong));
				}else {
					hsmwOrderBalance.setSettlementVolume(String.valueOf(driverVolume));
				}
			}
		}else {
			hsmwOrderBalance.setOutputVolume("0");
			hsmwOrderBalance.setDifferenceVolume(orderBalance.getRealVolume());
			hsmwOrderBalance.setSettlementVolume("0");
		}
		// 金额 单价*产值方量
		if(StringUtils.isNotBlank(orderBalance.getMonovalent())){
			if(StringUtils.equals("0.0",hsmwOrderBalance.getOutputVolume())){
				hsmwOrderBalance.setMoney("0");
			}else {
				// 产值方量
				Double output = Double.valueOf(hsmwOrderBalance.getOutputVolume());
				//单价
				Double monovalent = Double.valueOf(orderBalance.getMonovalent());
				DecimalFormat df = new DecimalFormat("#.0");
				String money = df.format(output * monovalent);
				if(StringUtils.equals(".0",money)){
					money = "0";
				}
				hsmwOrderBalance.setMoney(money);
			}
		}
		hsmwOrderBalanceMapper.updateById(hsmwOrderBalance);
		return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
	}

	public DataResponse findOrderBalanceByTime(String startTime, String endTime,String id) {

		List<HsmwOrderBalance> hsmwOrderBalances = hsmwOrderBalanceMapper.findOrderBalanceByTime(startTime,endTime,id);
		return new DataResponse(hsmwOrderBalances);
	}

	public DataResponse insertBalanceOnRecord() {

		List<HsmwOrderBalance> hsmwOrderBalances = hsmwOrderBalanceMapper.findOrderBalanceInfo();

		for (HsmwOrderBalance hsmwOrderBalance : hsmwOrderBalances) {
			HsmwConstructionPosition position = hsmwConstructionPositionService.getOne(new LambdaQueryWrapper<HsmwConstructionPosition>().eq(HsmwConstructionPosition::getOrderId, hsmwOrderBalance.getOrderId()));
			String concreteNum = hsmwConcreteInfoMapper.findConcreteNumByPosionId(position.getId());
			hsmwOrderBalance.setConcreteNum(concreteNum);
			hsmwOrderBalance.setStatementsTime(hsmwOrderBalance.getEndTime());
			String vehicleId = hsmwOrderBalance.getVehicleId();
			String orderId = hsmwOrderBalance.getOrderId();
			HsmwOrder order = hsmwOrderService.getById(orderId);
			HsmwItem hsmwItem = hsmwItemService.getById(order.getItemId());

			Double driverVolume = Double.valueOf(hsmwOrderBalance.getRealVolume());
			if(StringUtils.isNotNull(hsmwItem) && StringUtils.isNotBlank(hsmwItem.getSettlementPrice()) && !StringUtils.equals("0",hsmwItem.getSettlementPrice())){
				DecimalFormat df = new DecimalFormat("#.0");
				hsmwOrderBalance.setMonovalent(hsmwItem.getSettlementPrice());
				Double monovalent = Double.valueOf(hsmwOrderBalance.getMonovalent());
				String money = df.format(driverVolume * monovalent);
				hsmwOrderBalance.setMoney(money);
			}else {
				hsmwOrderBalance.setMonovalent(hsmwItem.getSettlementPrice());
				hsmwOrderBalance.setMoney("0");
			}
			HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(vehicleId);
			hsmwOrderBalance.setVehicleType(hsmwVehicle.getVehicleType());
			hsmwOrderBalance.setDifferenceVolume(hsmwOrderBalance.getRealVolume());
			hsmwOrderBalanceMapper.insert(hsmwOrderBalance);
		}

		return new DataResponse();
	}

	public DataResponse updateOrderBalances(HsmwOrderBalance hsmwOrderBalance) {

		if(hsmwOrderBalance == null){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"传递数据不可为空");
		}
		if(StringUtils.isBlank(hsmwOrderBalance.getId())){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"id不可为空");
		}
		hsmwOrderBalanceMapper.updateById(hsmwOrderBalance);
		return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
	}

    public List<HsmwLeasingCompany> getAvaliableSelfCompany(HashMap param) {
		return hsmwLeasingCompanyMapper.getAvaliableSelfCompany(param);
    }
}
